/**
 *九点平滑算法
 *作者：LG
 *时间：
 *依赖：
无
 */


function NinePointsSmoothing()
{
}


//将一维数组转化为二维数组
NinePointsSmoothing.prototype.transformToMatrix = function (values, m, n)
{
    let matrix = [];
    let row;
    for (let i = 0; i < m; i++)
    {
        row = new Array(n)
        for (let j = 0; j < n; j++)
        {
            row[j] = values[j + i * n];
        }
        matrix.push(row);
    }
    return matrix;
}

//将二维数组转换为一维数组
NinePointsSmoothing.prototype.transformToValues = function (matrix, m, n)
{
    let values = [];
    for (let i = 0; i < m; i++)
    {
        for (let j = 0; j < n; j++)
        {
            values.push(matrix[i][j]);
        }
    }
    return values;
}



//九点平滑一次
NinePointsSmoothing.prototype.smooth = function (matrix, m, n, p, q)
{
    if (!Array.isArray(matrix) || matrix.length == 0 || m < 3 || n < 3)
        return matrix;



    p = p || 0.5;
    q = q || 0.25;

    const p1 = p / 4;
    const q1 = q / 4;


    //九点平滑算法
    //中心区域点计算
    for (let i = 1; i < m - 1; i++)
    {
        for (let j = 1; j < n - 1; j++)
        {
            // matrix[i][j] = matrix[i][j] + p1*(f2+f4+f6+f8-4*matrix[i][j])+q1*(f1+f3+f5+f7-4*matrix[i][j]);
            matrix[i][j] = matrix[i][j] + p1 * (matrix[i][j - 1] + matrix[i + 1][j] + matrix[i][j + 1] + matrix[i - 1][j] - 4 * matrix[i][j]) + q1 * (matrix[i - 1][j - 1] + matrix[i + 1][j - 1] + matrix[i + 1][j + 1] + matrix[i - 1][j + 1] - 4 * matrix[i][j]);
        }
    }

    //首尾行计算
    for (let j = 1; j < n - 1; j++) 
    {
        //首行点计算
        matrix[0][j] = (matrix[0][j - 1] + matrix[1][j - 1] + matrix[1][j] + matrix[1][j + 1] + matrix[0][j + 1]) / 5.0;

        //尾行点计算
        matrix[m - 1][j] = (matrix[m - 1][j - 1] + matrix[m - 2][j - 1] + matrix[m - 2][j] + matrix[m - 2][j + 1] + matrix[m - 1][j + 1]) / 5.0;
    }


    //左右边计算
    for (let i = 1; i < m - 1; i++) 
    {
        //左边计算
        matrix[i][0] = (matrix[i - 1][0] + matrix[i - 1][1] + matrix[i][1] + matrix[i + 1][1] + matrix[i + 1][0]) / 5.0;

        //右边计算
        matrix[i][n - 1] = (matrix[i - 1][n - 1] + matrix[i - 1][n - 2] + matrix[i][n - 2] + matrix[i + 1][n - 2] + matrix[i + 1][n - 1]) / 5.0
    }

    //四角点计算
    matrix[0][0] = (matrix[0][1] + matrix[1][1] + matrix[1][0]) / 3.0
    matrix[0][n - 1] = (matrix[0][n - 2] + matrix[1][n - 2] + matrix[1][n - 1]) / 3.0
    matrix[m - 1][0] = (matrix[m - 2][0] + matrix[m - 2][1] + matrix[m - 1][1]) / 3.0
    matrix[m - 1][n - 1] = (matrix[m - 2][n - 1] + matrix[m - 2][n - 2] + matrix[m - 1][n - 2]) / 3.0

    return matrix;

}

//九点平滑Times次
NinePointsSmoothing.prototype.smoothWithTimes = function (matrix, m, n, p, q, times)
{
    if (Number.isInteger(times) && times > 0)
    {
        for (let i = 0; i < times; i++)
        {
            matrix = this.smooth(matrix, m, n, p, q);
        }
    }

    return matrix;
}


